import React, { Component } from 'react'
import Header from '../../components/Header/Header'
import './Home.less'
import { FireFill } from 'antd-mobile-icons'
import { countTime } from '../../filters/index'

import Goods from './components/Goods/Goods'
import Groupon from './components/Groupon/Groupon'
import New from './components/New/New'
import Seckill from './components/Seckill/Seckill'
import { Link } from 'react-router-dom'

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { getCates, getGroupon, getN, getNews, getSeckill, showGoods, actions, getNewsTime } from '../../store/modules/home'

class Home extends Component {
  render() {
    let { news, showGoods, groupon, seckill, cates, n,newsTime, homeFn: { changeN } } = this.props;
    console.log(this.props)
    return (
      <div className='home'>
        {/* 1.公共头部 */}
        <Header title="首页"></Header>
        {/* 2.新人专享 */}
        <New news={news} newsTime={newsTime}></New>
        {/* 3.导航栏 */}
        <div className='nav'>
          {cates.length > 0 ? <>
            {cates.map(item => {
              return <Link to="/index/cate" className='item' key={item.id}>
                <span><FireFill /></span>
                <p>{item.catename}</p>
              </Link>
            })}
          </> : null}
        </div>
        {/* 4.秒杀 */}
        <Seckill seckill={seckill}></Seckill>
        {/* 5.万人团 */}
        <Groupon groupon={groupon}></Groupon>
        {/* 6.首页商品列表 */}
        <Goods showGoods={showGoods} n={n} changeN={(n) => changeN(n)}></Goods>
      </div>
    )
  }
  componentDidMount() {
    let {requestNew,requestGoods,requestGroupon,requestSeckill,requestCates}=this.props.homeFn;
    requestNew();
    requestGoods();
    requestGroupon();
    requestSeckill();
    requestCates();
    // 页面倒计时
    let newsTime = countTime('2022-5-30');
    // 如果倒计时没结束则开启定时器，修改仓库里的数据
    if(newsTime.leftTime>0){
       this.timer = setInterval(() => {
        newsTime = countTime('2022-5-30');
      this.props.homeFn.changeNewsTime(newsTime)
    }, 1000)
    }else{
      clearInterval(this.timer)
    }
  }
  componentWillUnmount() {
    clearInterval(this.timer)
  }
}

// 取数据
const mapStateToProps = state => {
  return {
    news: getNews(state),
    showGoods: showGoods(state),
    groupon: getGroupon(state),
    seckill: getSeckill(state),
    cates: getCates(state),
    n: getN(state),
    newsTime: getNewsTime(state)
  }
}
// 取方法
const mapDispatchToProps = dispatch => {
  return {
    homeFn: bindActionCreators(actions, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Home)
